using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using HengTong.Model.Db.System;
using TiaoTaoHelper.Wtm.Models;
using WalkingTec.Mvvm.Core.Extensions;

namespace HengTong.ViewModel;

public class BaseListVm<TModel, TSearcher> : BasePagedListVM<TModel, TSearcher>
    where TModel : TopBasePoco
    where TSearcher : BaseSearcher
{
    /// <summary>
    /// 检查当前登录用户是否为待办审批人
    /// </summary>
    /// <returns>符合条件的工作流列表</returns>
    protected List<SysWorkflow> GetMyApproves()
    {
        Type modelType = ModelType.GetParentWorkflowPoco();
        if (!(modelType != null)) return new List<SysWorkflow>();
        
        var list = DC.Set<SysWorkflow>()
            .AsNoTracking()
            .Where(x => modelType.FullName == x.ModelType)
            .Where(x => x.TenantCode == Wtm.LoginUserInfo.CurrentTenant)
            .ToList();
            
        var positionList = DC.Set<SysUserJobPosition>()
            .AsNoTracking()
            .Include(e => e.JobPosition)
            .ThenInclude(e => e.Roles)
            .Where(e => e.UserId == Guid.Parse(Wtm.LoginUserInfo.UserId))
            .Select(e => e.JobPosition)
            .ToList();
            
        return list.Where(e => 
            (e.Type == SysWorkflowType.用户 && e.UserCode == Wtm.LoginUserInfo.ITCode) ||
            (e.Type == SysWorkflowType.角色 && Wtm.LoginUserInfo.Roles.Any(x => x.ID == e.RoleId)) ||
            (e.Type == SysWorkflowType.部门 && Wtm.LoginUserInfo.Groups.Any(x => x.ID == e.GroupId)) ||
            (e.Type == SysWorkflowType.岗位 && positionList.Any(x => x.GroupId == e.GroupId && x.Roles.Any(r => r.RoleId == e.RoleId)))
        ).ToList();
    }
}
